<template>
  <view class="publish-container">

    <!-- 上传通道 -->
    <block>
    <view class="item-container default-box-shadow">
      <Title title="上传通道" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#333'
      }">
      <!-- #ifdef H5 -->
        <view class="create-album" @click="goBack">
          <!-- <u-icon name="plus" color="#56d39d" size="24"></u-icon> -->
          <text class="huiju-iconfont huiju-icon-fanhui1"></text>
          <text>返回</text>
        </view>  
      <!-- #endif -->  
      </Title>
      <view class="select-pass-container">
        <view class="pass-item pass-item1"
          :class="{
            'pass-item-active': uploadForm.show_type === 0
          }"
          @click="handleShowType(0)">
          <view class="pass-title">
            默认通道
          </view>
          <view class="pass-des">
            审核较严：过审展示所有平台
          </view>
        </view>
        <view class="pass-item"
          :class="{
            'pass-item-active': uploadForm.show_type === 1
          }"
          @click="handleShowType(1)">
          <view class="pass-title">
            快手/微信/QQ通道
          </view>
          <view class="pass-des">
            审核宽松：过审仅展示快微Q平台
          </view>
        </view>
      </view>
    </view>
  </block>

    <view class="item-container default-box-shadow">
      <Title title="素材类型" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#333'
      }">
      </Title>
      <view class="type-container">
        <view
          v-for="(item, index) in artworksTypeAllListData"
          :key="item.id"
          class="type-item"
          :class="{
            'active-item': index === currentArtworksType
          }"
          @click="changeType(item, index)">{{ item.type_name }}</view>
      </view>
    </view>

    <!-- 作品分类 -->
    <view v-if="currentCategoryList && currentCategoryList.length > 0" class="item-container default-box-shadow">
      <Title title="素材分类（选填）" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#333'
      }"></Title>
      <view class="type-container">
        <view
          v-for="item in currentCategoryList"
          :key="item.id"
          class="type-item"
          :class="{
            'active-item': item.checked
          }"
          @click="selectArtworksCategory(item.id)">{{ item.category_name }}</view>
      </view>
    </view>
    <!-- 作品分类 -->
    <view class="item-container default-box-shadow">
      <Title :title="uploadParams.artwroksTitle" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#333'
      }"></Title>
      <view class="upload-artworks-container">
        <!-- 微信小程序和h5上传 -->
        <WechatH5Upload
          v-if="(isWechatH5 && initJssdkFlag && uploadForm.type != 3)"
          ref="uUpload"
          :action="uploadParams.action"
          :header="{
            'Authorization': 'Bearer ' + token // token
          }"
          height="200"
          upload-text="选择"
          :form-data="uploadForm"
          :limitType="uploadParams.limitType"
          :source-type="['album']"
          :max-count="uploadParams.maxCount"
          :type="uploadParams.uploadType"
          :uploadText="uploadParams.uploadText"
          :artworksType="uploadForm.type"
          del-bg-color="#56d39d"
          :auto-upload="false"
          @on-uploaded="uploadSuccess"
          @on-choose-complete="chooseComplete"
          @initJssdk="initJssdkCallback"></WechatH5Upload>
        <Upload
          v-else
          ref="uUpload"
          :action="uploadParams.action"
          :header="{
            'Authorization': 'Bearer ' + token // token
          }"
          height="200"
          upload-text="选择"
          :form-data="uploadForm"
          :limitType="uploadParams.limitType"
          :source-type="['album']"
          :max-count="uploadParams.maxCount"
          :type="uploadParams.uploadType"
          :uploadText="uploadParams.uploadText"
          :artworksType="uploadForm.type"
          del-bg-color="#56d39d"
          :auto-upload="false"
          @on-uploaded="uploadSuccess"
          @on-choose-complete="chooseComplete"></Upload>
        
          <view v-if="uploadForm.type === 5" class="artworks-title">
            <u-input
              v-model="uploadForm.title"
              placeholder="请输入素材的名称(选填)"
              border
              clearable
            ></u-input>
          </view>
      </view>
    </view>

    <!-- 创建专辑 -->
    <view class="item-container default-box-shadow">
      <Title title="作品专辑（选填）" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#333'
      }">
        <view class="create-album" @click="createAlbum.popupShow = true">
          <!-- <u-icon name="plus" color="#56d39d" size="24"></u-icon> -->
          <text class="huiju-iconfont huiju-icon-ico_classify_unfold"></text>
          <text>创建专辑</text>
        </view>
      </Title>
      <view class="type-container">
        <block v-if="albumList && albumList.length > 0">
          <view
            v-for="item in albumList"
            :key="item.id"
            class="type-item text-overflow"
            :class="{
              'active-item': item.checked
            }"
            @click="selectArtworksAlbum(item.id)">{{ item.name }}</view>
        </block>
        <view v-else class="album-container">
          没有查询到您创建的专辑
        </view>
      </view>
    </view>

    <!-- 提示 -->
    <view class="tips-container">
      <text>温馨提示：{{ uploadParams.uploadText }}格式，一次最多上传{{ uploadParams.maxCount }}个素材;</text>
      <text v-if="uploadNumConfig.max_upload_num > 0">今日限额{{ uploadNumConfig.max_upload_num }}张，已上传{{ uploadNumConfig.todayUploadNum }}张</text>
    </view>

    <!-- 上传按钮确定 -->
    <view class="confirm-btn">
      <u-button
        class="btn"
        type="primary"
        shape="circle"
        hover-class="none"
        :custom-style="{
          backgroundColor: '#56d39d',
          fontWeight: 700
        }"
        @click="sumbitArtworks"
        :disabled="uploadNumConfig.surplus <= 0"
        :loading="btnLoading">确认上传</u-button>
    </view>

    <!-- 保护隐私协议 -->
    <view class="agreement">
      <u-checkbox-group active-color="#56d39d">
        <u-checkbox v-model="agreement" size="40"></u-checkbox><text @click="handleAgreement">同意《用户服务协议》及《隐私政策》</text>
      </u-checkbox-group>
    </view>

    <!-- 创建专辑 -->
    <CreateArtworksAlbum
      :popup-show="createAlbum.popupShow"
      :popup-title="createAlbum.popupTitle"
      :album-info="createAlbum.albumInfo"
      @close="close"
      @success="findAlbumByAuthorIdAndTypeIdFn"></CreateArtworksAlbum>
  </view>
</template>

<script>
  import { allArtworksCategory } from '@/api/user';
  import { findAlbumByAuthorIdAndTypeId, checkMaxUploadMax } from '@/api/artworks';
  import Title from '@/components/title/title';
  import Upload from '@/components/upload/upload';
  import WechatH5Upload from '@/components/upload/wechatUpload';
  import CreateArtworksAlbum from '@/components/createArtworksAlbum/createArtworksAlbum';
  import { mapGetters } from 'vuex';
  import config from '@/utils/config';
  import wechatH5 from '@/utils/wechatH5';
  export default {
    components: {
      Title,
      Upload,
      WechatH5Upload,
      CreateArtworksAlbum
    },
    data() {
      return {
        show_type: 0,
        agreement: true,
        initJssdkFlag: true,
        createAlbum: {
          popupShow: false,
          popupTitle: '创建新专辑',
          albumInfo: {
            name: '', // 专辑名称
            is_top: '', // 是否置顶
            author_id: '', // 主页id
            artworks_type_id: '' // 作品类型
          }
        },
        currentArtworksType: 0,
        artworksCategoryList: [], // 全部分类
        currentCategoryList: [], // 当前作品类型的分类
        albumList: [], // 专辑列表
        btnLoading: false,
        uploadParams: {
          limitType: ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp'],
          maxCount: 50,
          uploadType: 'image',
          action: `${config.baseApi}/upload/artworks`, // 作品上传
          // action: `${config.baseApi}/upload/uploadImg`,
          fileList: [],
          uploadText: '支持png/jpg',
          artwroksTitle: '上传素材',
        },
        uploadForm: {
          title: '', // 作品名称
          author_id: '',
          type: null, // 作品类型
          show_type: 0,
          cate_id: '', // 作品分类
          album_id: '', // 专辑id
        },
        defaultAlbumId: '', // 默认专辑id
        isWechatH5: false,
        uploadNumConfig: {
          max_upload_num: 0,
          surplus: 0,
          todayUploadNum: 0
        }
      }
    },
    computed: {
      ...mapGetters([
        'artworksTypeAllListData',
        'userInfo',
        'token',
        'version',
      ])
    },
    onLoad(options) {
      this.uploadForm.author_id = options.author_id;
      this.createAlbum.albumInfo.author_id = options.author_id;
      if (options.album_id) {
        this.defaultAlbumId = options.album_id;
      }
      this.currentArtworksType = parseInt(options.currentArtworksType);
      this.getAllArtworksCategory();
      setTimeout(() => {
        this.createAlbum.albumInfo.artworks_type_id = this.$store.state.artworksTypeAllListData[this.currentArtworksType].id;
        this.uploadParams.artwroksTitle = `上传${this.artworksTypeAllListData[this.currentArtworksType].type_name}`;
        this.uploadForm.type = this.artworksTypeAllListData[this.currentArtworksType].id;
        this.onloadType();
        this.findAlbumByAuthorIdAndTypeIdFn(); // 获取专辑
      }, 200);
      this.getCheckMaxUploadMax();
    },
    onShow() {
      // #ifdef H5
      if (wechatH5.isWechat()) {
        this.isWechatH5 = true;
      }
      // #endif
    },
    methods: {

      // 检查当天上传作品的次数
      getCheckMaxUploadMax() {
        checkMaxUploadMax().then(result => {
          console.log(result);
          if (result && result.data) {
            this.uploadNumConfig = result.data;
          }
        })
      },

      // 选择通道
      handleShowType(type) {
        this.uploadForm.show_type = type;
        if (type === 1) {
          uni.showModal({
            title: '温馨提示',
            content: `使用该通道上传素材审核标准较为宽松，但是不显示在抖音小程序端，仅显示快手 微信 qq端小程序！`,
            confirmText: '确定',
            showCancel: false,
            confirmColor: '#56d39d',
            success: ({ confirm, cancel }) => {
              if (confirm) {
                this.goCode();
              }
            }
          })
        }
      },

      // 公众号是否配置成功
      initJssdkCallback(res) {
        if (res === 'success') {
          this.initJssdkFlag = true;
        } else {
          this.initJssdkFlag = false;
        }
      },

      // 获取达人主页下的全部专辑
      findAlbumByAuthorIdAndTypeIdFn() {
        findAlbumByAuthorIdAndTypeId({
          author_id: this.uploadForm.author_id,
          artworks_type_id: this.createAlbum.albumInfo.artworks_type_id
        }).then(result => {
          if (result && result.data && result.data.length > 0) {
            let list = result.data;
            list.forEach(item => {
              if (item.id == this.defaultAlbumId) {
                item.checked = true;
                this.uploadForm.album_id = item.id;
              } else {
                item.checked = false;
              }
            })
            this.albumList = list;
          } else {
            this.albumList = [];
          }
        })
      },

      // 前往同意
      handleAgreement() {
        uni.navigateTo({ url: '/pages/about/agreement' })
      },

      // 选择专辑
      selectArtworksAlbum(album_id) {
        let albumList = this.albumList;
        albumList.forEach(item => {
          if (item.id === album_id) {
            item.checked = !item.checked;
            this.uploadForm.album_id = item.checked ? item.id : '';
          } else {
            item.checked = false;
          }
        })
      },

      // 获取作品全部分类
      getAllArtworksCategory() {
        allArtworksCategory().then(result => {
          if (result && result.data && result.data.length > 0) {
            let list = result.data;
            list.forEach(item => {
              item.checked = false;
            })
            this.artworksCategoryList = list;
            this.currentCategoryList = this.currentArtworksType ? list.filter(item => item.category_type === this.artworksTypeAllListData[this.currentArtworksType].id) : list.filter(item => item.category_type === this.artworksTypeAllListData[0].id);
          }
        })
      },

      // 选择作品分类
      selectArtworksCategory(cate_id) {
        let currentCategoryList = this.currentCategoryList;
        currentCategoryList.forEach(item => {
          if (item.id === cate_id) {
            item.checked = !item.checked;
            this.uploadForm.cate_id = item.checked ? item.id : '';
          } else {
            item.checked = false;
          }
        })
      },

      // 加载类型
      onloadType(type) {
        let typeId = this.artworksTypeAllListData[this.currentArtworksType].id;
        if (typeId == 1 || typeId == 2 || typeId == 6) {
          this.uploadParams.uploadText = '支持png/jpg';
          this.uploadParams.limitType = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp', 'mp4'];
          this.uploadParams.uploadType = 'image';
          this.uploadParams.maxCount = 50;
        } else if (typeId == 3) {
          this.uploadParams.uploadText = '支持png/jpg/gif';
          this.uploadParams.limitType = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp', 'gif'];
          this.uploadParams.uploadType = 'image';
          this.uploadParams.maxCount = 50;
        } else if (typeId == 4 || typeId == 5 || typeId == 8) {
          this.uploadParams.uploadText = '支持mp4';
          this.uploadParams.limitType = ['mp4', 'MP4'];
          this.uploadParams.uploadType = 'video';
          this.uploadParams.maxCount = 1;
        }
      },

      // 选择作品类型
      changeType(itemData, clickIndex) {
        if (itemData.id == 7) {
          uni.navigateTo({
            url: `/pages/publish/textTemplate?author_id=${this.uploadForm.author_id}`
          })
          return;
        } else if (itemData.id == 9) {
          uni.navigateTo({
            url: `/pages/tool/toolCategory?author_id=${this.uploadForm.author_id}`
          })
          return;
        } else if (itemData.id == 11) {
          uni.navigateTo({
            url: `/pages/wechatCircle/uploadWechatCircle?author_id=${this.uploadForm.author_id}`
          })
          return;
        } else if (itemData.id == 1 || itemData.id == 2 || itemData.id == 6) {
          this.uploadParams.uploadText = '支持png/jpg';
          this.uploadParams.limitType = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp', 'mp4'];
          this.uploadParams.uploadType = 'image';
          this.uploadParams.maxCount = 50;
        } else if (itemData.id == 3) {
          this.uploadParams.uploadText = '支持png/jpg/gif';
          this.uploadParams.limitType = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'webp', 'gif'];
          this.uploadParams.uploadType = 'image';
          this.uploadParams.maxCount = 50;
        } else if (itemData.id == 4 || itemData.id == 5 || itemData.id == 8) {
          this.uploadParams.uploadText = '支持mp4';
          this.uploadParams.limitType = ['mp4', 'MP4'];
          this.uploadParams.uploadType = 'video';
          this.uploadParams.maxCount = 1;
        }
        this.currentArtworksType = clickIndex;
        this.uploadParams.artwroksTitle = itemData.id == 3 ? `上传${itemData.type_name}（添加后可添加原声视频）` : `上传${itemData.type_name}`;
        this.uploadForm.type = itemData.id;
        this.uploadForm.title = '';
        this.createAlbum.albumInfo.artworks_type_id = itemData.id;
        this.uploadForm.cate_id = '';
        this.uploadForm.album_id = '';
        this.currentCategoryList = this.artworksCategoryList.filter(item => item.category_type == itemData.id);
        this.findAlbumByAuthorIdAndTypeIdFn(this.uploadForm.author_id, this.uploadForm.type);
        // console.log(this.$refs.uUpload)
        this.$refs.uUpload.resetList(); // 切换分类重置上传文件列表
      },

      // 确定提交
      sumbitArtworks() {
        if (!this.agreement) {
          uni.showToast({
            title: '请勾选同意《用户服务协议》及《隐私政策》，在提交',
            icon: 'none',
            mask: false,
          })
          return;
        }
        this.btnLoading = true;
        uni.showToast({
          title: '上传中',
          icon: 'loading',
          mask: true,
          duration: 60 * 1000
        })
        this.$refs.uUpload.upload();
      },

      // 上传成功
      uploadSuccess(data, index, lists, name) {
        this.btnLoading = false;
        if (data && data.length > 0) {
          this.uploadForm.title = '';
          this.$refs.uUpload.deleteAllItem(); // 上传成功清除所有作品
          this.selectArtworksAlbum(''); // 重置专辑
          uni.showToast({
            title: '上传成功',
            icon: 'success',
            mask: true,
          })
          setTimeout(function() {
            let pages = getCurrentPages();
            let pagesLength = pages.length;

            if (pagesLength > 1) {
              uni.navigateBack({
                delta: 1,
              })
            } else {
              let pages = getCurrentPages();
              let pagesLength = pages.length;

              if (pagesLength > 1) {
                uni.navigateBack({
                  delta: 1,
                })
              } else {
                uni.switchTab({ url: '/pages/creativeCenter/index' });
              }
            }
          }, 1500)
        } else {
          uni.showToast({
            title: '至少选择一张图片或上传失败请重试！',
            icon: 'none',
            mask: false,
          })
        }
      },

      // 选择图片
      chooseComplete(list) {
        // console.log(list)
      },

      // 关闭
      close() {
        this.createAlbum.popupShow = false;
      },

      // 返回
      goBack() {
        uni.switchTab({ url: '/pages/creativeCenter/index' })
      }
    }
  }
</script>

<style lang="scss" scoped>
  page{
    background-color: #f5f5f5;
  }
  .publish-container{
    padding: 32rpx;

    .item-container{
      background-color: #fff;
      padding: 24rpx 24rpx 0 24rpx;
      border-radius: 16rpx;
      margin-bottom: 12rpx;
    }

    .type-container{
      display: flex;
      flex-wrap: wrap;

      .type-item{
        max-width: 30%;
        min-width: 30%;
        text-align: center;
        height: 54rpx;
        line-height: 54rpx;
        background-color: #F5F5F9;
        margin-bottom: 24rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #666;


        &:nth-child(3n -1) {
          margin: 0 5%;
        }
      }

      .active-item{
        background-color: $uni-color-primary2;
        color: #fff;
      }
    }

    .artworks-title{
      padding-top: 24rpx;
    }

    .album-container{
      padding: 24rpx;
      text-align: center;
      font-size: 24rpx;
      color: #888;
    }

    .upload-artworks-container{
      padding-bottom: 24rpx;
    }

    .tips-container{
      font-size: 24rpx;
      color: #888;
      padding: 24rpx 0;
    }

    .confirm-btn{
      padding: 24rpx 0;
    }

    .create-album{
      position: absolute;
      right: 0;
      top: 0;
      margin: auto;
      font-size: 26rpx;
      font-weight: 400;
      color: $uni-color-primary;
      background: #f3f7fb;
      padding: 6rpx 24rpx;
      border-radius: 24rpx;
    }

    .agreement{
      margin-top: 24rpx;
      font-size: 24rpx;
    }
  }

  .select-pass-container{
    display: flex;
    padding-bottom: 24rpx;

    .pass-item{
      flex: 1;
      padding: 8rpx;
      background: #f7f7f8;
      border: 2rpx solid #e5e5e5;
      border-radius: 10rpx;
      transition: .1s;
    }
    .pass-item-active{
      background: #fff;
      border: 1px solid #56d39d;
      color: #56d39d;
    }
    .pass-item1{
      margin-right: 24rpx;
    }
    .pass-title{
      text-align: center;
      font-size: 28rpx;
      margin-bottom: 12rpx;
    }
    .pass-des{
      font-size: 24rpx;
    }
  }
</style>
